﻿namespace EFS.RC.CCC.Application.EndPoints.Models
{
	/// <summary>
	/// Customer role of end point
	/// </summary>
	internal class Customer : EFS.RC.CCC.Application.EndPoints.EndPoint
	{
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="ownerUri"></param>
		public Customer(Microsoft.Rtc.Collaboration.ApplicationEndpointSettings applicationEndpointSettings)
			: base(applicationEndpointSettings)
		{
			// subscribe to events
			OnPreEndPointStartup += SetupEndPointRole;
			OnPreEndPointShutDown += Cleanup;
		}

		#region Initalization and startup

		/// <summary>
		/// Agents application
		/// </summary>
		public EFS.RC.CCC.Application.EndPoints.Models.Agent AgentApplicationModel
		{
			get { return EFS.RC.CCC.Platform.Instance.GetAgentAplication; }
		}

		/// <summary>
		/// Setup the end point for Customer role
		/// </summary>
		private void SetupEndPointRole(Microsoft.Rtc.Collaboration.ApplicationEndpoint applicationEndpoint)
		{
			// log
			EFS.EventLog.Log.LogInfo("EFS.RC.CCC.Application.EndPoints.Models:SetupEndPointRole", this);

			// register for calls
			applicationEndpoint.RegisterForIncomingCall<Microsoft.Rtc.Collaboration.AudioVideo.AudioVideoCall>(OnIncomingAudioVideoCallCalls);
		}

		#endregion

		#region Runtime

		/// <summary>
		/// On incomming audio-video calls
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="args"></param>
		private void OnIncomingAudioVideoCallCalls(object sender, Microsoft.Rtc.Collaboration.CallReceivedEventArgs<Microsoft.Rtc.Collaboration.AudioVideo.AudioVideoCall> args)
		{
			// Must be new call
			if (args.IsNewConversation && args.CallToBeReplaced == null)  //New Acd customer session
			{
				// make a new session
				EFS.RC.CCC.Sessions.Customer customerSession = new Sessions.Customer(this, args.Call);

				//add the session to the list.
				// TODO: add session to list to track

				// start session
				customerSession.BeginStartup();
			}
			else
			{
				// decline call
				args.Call.Decline();
			}
		}

		#endregion

		#region Cleanup

		/// <summary>
		/// Clean-up 
		/// </summary>
		/// <param name="applicationEndpoint"></param>
		private void Cleanup(Microsoft.Rtc.Collaboration.ApplicationEndpoint applicationEndpoint)
		{
			// log
			EFS.EventLog.Log.LogInfo("Cleanup", this);

			//unregister the events
			applicationEndpoint.UnregisterForIncomingCall<Microsoft.Rtc.Collaboration.AudioVideo.AudioVideoCall>(OnIncomingAudioVideoCallCalls);
		}

		#endregion
	}
}
